import { routerRedux } from 'dva/router'
// import { stringify } from 'querystring'
import { fakeAccountLogin, getFakeCaptcha, getWxQrcodeData, smsValidator } from '@/services/login'
import { getPageQuery } from '@/utils/utils'
import Cookies from 'universal-cookie'
// import { message } from 'antd'
const cookies = new Cookies()

const USER_KEY = 'eva_user'
const TOKEN_KEY = 'auth_token'
const EXT_KEY = 'eva_ext'

const Model = {
  namespace: 'login',
  state: {
    // true,false, 'needValid'
    status: undefined,
    //
    needValidAccount: '',
  },
  effects: {
    *loginJump() {
      const urlParams = new URL(window.location.href)
      const params = getPageQuery()
      let { redirect } = params

      if (redirect) {
        const redirectUrlParams = new URL(redirect)

        if (redirectUrlParams.origin === urlParams.origin) {
          // redirect = redirect.substr(urlParams.origin.length)

          if (redirect.match(/^\/.*#/)) {
            redirect = redirect.substr(redirect.indexOf('#') + 1)
          }
        } else {
          window.location.href = '/'
          return
        }
      }
      // yield put(routerRedux.replace(redirect || '/'))
      window.location.href = '/'
    },

    *login({ payload }, { call, put }) {
      // yield put({
      //   type: 'changeLoginStatus',
      //   payload: {
      //     status: 'needValid',
      //   },
      // })
      const response = yield call(fakeAccountLogin, payload)

      cookies.set(USER_KEY, response.data.user || {}, { path: '/' })
      if (response && response.success) {
        // 是否存在token
        if (response.data.token) {
          console.log('has token')
          yield put({
            type: 'changeLoginStatus',
            payload: {
              status: response.success,
            },
          })

          yield put({
            type: 'loginJump',
          })
        } else {
          // message.success('验证码已发送')
          yield put({
            type: 'changeLoginStatus',
            payload: {
              status: 'needValid',
              needValidAccount: response.data.user.account,
            },
          })
        }
        //
      } else {
        yield put({
          type: 'updateState',
          payload: {
            status: 'error',
            type: 'account',
          },
        })
      }
    },

    *getQrcodeData({ payload }, { call }) {
      const res = yield call(getWxQrcodeData)
      if (payload.callback) payload.callback(res)
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload)
    },

    *smsValidator({ payload }, { call, put, select }) {
      const account = yield select(state => {
        return state.login.needValidAccount
      })

      const res = yield call(smsValidator, {
        account,
        code: payload.code,
      })

      if (res && res.success) {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: res.success,
          },
        })

        yield put({
          type: 'loginJump',
        })
      } else {
        yield put({
          type: 'updateState',
          payload: {
            status: 'error',
            // type: 'account',
          },
        })
      }
    },

    *logout(_, { put }) {
      console.info(' user log out ')
      // 删除token
      cookies.remove(TOKEN_KEY, { maxAge: -1, path: '/' })
      cookies.remove(USER_KEY, { maxAge: -1, path: '/' })
      cookies.remove(EXT_KEY, { maxAge: -1, path: '/' })

      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
        },
      })

      const { redirect } = getPageQuery() // redirect

      if (window.location.pathname !== '/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/login',
            // search: stringify({
            //   redirect: window.location.href,
            // }),
          }),
        )
      }
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
    changeLoginStatus(state, { payload }) {
      return { ...state, ...payload }
    },
  },
}
export default Model
